import redis


from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication #继承认证类


class Authtication(BaseAuthentication):
    def authenticate(self, request):
        try:
            request_token = request.META.get('HTTP_AUTHENTICATE',"")
            print("request_token",request_token)
            token,username = request_token.split(":")# 登录视图设置的token有 ：符号
            sr = redis.Redis(connection_pool='')
        except Exception as e:
            raise exceptions.AuthenticationFailed({"code": 405, "error": "请求错误，请重新登录"})

            # 判断登录是否有token
            if not token:
                raise exceptions.AuthenticationFailed({"code": 407,"error":"用户请求异常,未携带token"})

            # 判断 token 正确或者是否过期
            redis_token = sr.hget(username,"token")
            if request_token != redis_token:
                raise exceptions.AuthenticationFailed({"code": 405, "error": "请求错误，请重新登录"})



    def authenticate_header(self, request):
        pass